package csc.daonjpa.java.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Component;

import csc.daonjpa.java.controller.EntityManagerFactoryUtil;
import csc.daonjpa.java.domain.Customer;

/**
 * DAO class for Customer entity. This class contains all methods that inserts/updates/deletes
 * customer info
 * @author nvu3
 *
 */
@Component
public class CustomerDAO {
	
	/**
	 * @return all customers from Customer table
	 */
	public List<Customer> getCustomers() {
		
		// Obtains entity manager object
		EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();
		
		// Obtains transaction from entity manager
		EntityTransaction entr = entityManager.getTransaction();
		
		// -----------Begin transaction-----------
		List<Customer> customers = null;
		try {
			entr.begin();
			// Get a list of customers from DB
			TypedQuery<Customer> query = entityManager.createQuery("SELECT a FROM Customer a", Customer.class);
			customers = query.getResultList();
			entr.commit();
		} catch (Exception e) {
			entityManager.close();
		}
		// -----------End transaction-----------

		return customers;
		
	}
	
	/**
	 * Add customer to Customer table
	 * @param customer Customer entity that contains mapped with each column in Customer table
	 * @return
	 */
	public boolean addCustomer(Customer customer) {
		// Obtains entity manager object
		EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();
		
		// Obtains transaction from entity manager
		EntityTransaction entr = entityManager.getTransaction();
		
		try {
			// -----------Begin transaction-----------
			entr.begin();
			// Insert a row to Customer table
			entityManager.persist(customer);
			entr.commit();
		} catch (Exception e) {
			entityManager.close();
		}
		// -----------End transaction-----------
		
		return true;
	}
}
